package com.kelvem.saas.workbanch.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class BeanUtil implements ApplicationContextAware {
    
    private static ApplicationContext applicationContext;
    
    @Override
    public void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }
    
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> targetClz) {
        T beanInstance = null;
        //优先按type查
        try {
            beanInstance = applicationContext.getBean(targetClz);
            //按name查
            if (beanInstance == null) {
                String simpleName = targetClz.getSimpleName();
                //首字母小写
                simpleName = Character.toLowerCase(simpleName.charAt(0)) + simpleName.substring(1);
                beanInstance = (T) applicationContext.getBean(simpleName);
            }
        } catch (Exception ignored) {
        }
        return beanInstance;
    }
    
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName) {
        T beanInstance = null;
        try {
            //按name查
            beanInstance = (T) applicationContext.getBean(beanName);
        } catch (Exception ignored) {
        }
        return beanInstance;
    }
    
}
